package com.youlai.boot.system.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.boot.system.enums.OrderEnum;
import com.youlai.boot.system.model.entity.Order;
import com.youlai.boot.system.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 订单超时自动取消处理器
 *
 * @author youlai
 * @since 2025/3/25
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class OrderTimeoutCancelHandler {

    private final OrderService orderService;

    /**
     * 定时检查并取消超时未支付订单
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void cancelTimeoutOrders() {

        try {
            // 查询所有未支付且创建时间超过30分钟的订单
            List<Order> timeoutOrders = orderService.list(new LambdaQueryWrapper<Order>()
                    .eq(Order::getStatus, OrderEnum.UNPAID.getCode())
                    .lt(Order::getCreateTime, LocalDateTime.now().minus(30, ChronoUnit.MINUTES)));

            if (timeoutOrders.isEmpty()) {
                return;
            }

            // 逐个取消超时订单
            for (Order order : timeoutOrders) {
                try {
                    orderService.cancelOrder(order.getId());
                } catch (Exception e) {
                    log.error("自动取消订单{}失败: {}", order.getId(), e.getMessage(), e);
                }
            }

        } catch (Exception e) {
            log.error("执行超时订单自动取消任务时发生错误: {}", e.getMessage(), e);
        }
    }
}